<script setup>
defineOptions({
  name: 'AppLogin'
})
import { ref } from 'vue'
import { login, merge } from '@/api/login.js'
import { useUserStore } from '@/stores/user.js'
import { useRouter } from 'vue-router'
const userStore = useUserStore()
const router = useRouter()
const rule = ref({
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      min: 5,
      max: 15,
      message: '用户名字符长度在5-15之间',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^[\S]{5,16}$/,
      message: '密码不能存在空格，且长度为5-16',
      trigger: 'blur'
    }
  ],
  agree: [
    {
      validator(rule, value, callback) {
        if (value) callback()
        else callback(new Error('请同意阅读协议'))
      }
    }
  ]
})
const form = ref(null)
const userLogin = ref({
  account: 'heima282',
  password: 'hm#qd@23!',
  agree: true
})
const log = async () => {
  await form.value.validate()
  const res = await login({
    account: userLogin.value.account,
    password: userLogin.value.password
  })
  userStore.setUserInfo(res.result)
  merge()
  ElMessage.success('登录成功')
  router.push('/home')
}
</script>

<template>
  <div>
    <nav
      class="container navbar-nav flex-row align-items-center justify-content-between"
    >
      <router-link to="/home"
        ><img
          src="@/assets/logo.png"
          width="250"
          height="90"
          class="navbar-brand"
          alt=""
      /></router-link>
      <router-link to="/home" class="text-decoration-none text-dark"
        >返回首页<span class="text-info"> >> </span></router-link
      >
    </nav>
    <div class="bg row">
      <div class="col-3 offset-7 my-auto bg-white">
        <h5 class="text-center border-bottom py-3">账户登录</h5>
        <el-form
          ref="form"
          class="py-3"
          :rules="rule"
          :model="userLogin"
          status-icon
        >
          <el-form-item prop="account" label="用户名：">
            <el-input
              v-model="userLogin.account"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password" label="密&ensp;&ensp;码：">
            <el-input
              v-model="userLogin.password"
              placeholder="请输入密码"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item prop="agree">
            <el-checkbox v-model="userLogin.agree"
              >我已同意隐私条款和服务条款</el-checkbox
            >
          </el-form-item>
          <el-form-item>
            <el-button type="success" class="mx-auto w-100" @click="log"
              >点击登录</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
nav {
  height: 20vh;
}
.bg {
  background: url('@/assets/login-bg.png') no-repeat;
  background-size: cover;
  height: 60vh;
  background-position-x: -200px;
}
</style>
